package com.message.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.message.config.ConfigProperties;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DruidUtils {
    //定义数据库连接池数据源
    private volatile  static DruidDataSource druidDataSource=null;

    //    初始化数据库连接池
    static {
        if (druidDataSource == null) {
            synchronized (DruidUtils.class) {
                if (druidDataSource == null) {//双重校验锁，防止多线程环境下出现初始化多个线程池的情况
                    try {
                        JedisPoolUtil.initUserTable(); //重新初始化映射表缓存
                        druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(ConfigProperties.getProperties());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    //返回DataSource对象
    public static DataSource getDataSource() {
        return druidDataSource;
    }

    //    从连接池中获取数据库连接
    public static Connection getConnection() throws SQLException {
        Connection connection = null;
        connection = druidDataSource.getConnection();
        return connection;
    }

    private DruidUtils() {
    }

}
